#include "GraphicsBoard.h"
#include <QPainter>

GraphicsBoard::GraphicsBoard(QWidget*& w) {
  m_n = 0;
  gridWidth = 0.0f;
  m_board = nullptr;
}

// 绘画函数
void GraphicsBoard::paintEvent(QPaintEvent* event) {
  int n = m_n;
  // 确定方格边长、起始位置：根据窗口大小自动适应
  gridWidth = std::min(width(), height()) / (n + 2);
  float startX = gridWidth;
  float startY = gridWidth;

  QPainter painter(this);
  // 设置画笔：自适应线条宽度
  QPen pen;
  pen.setWidth(gridWidth / 12);
  painter.setPen(pen);
  painter.setRenderHint(QPainter::Antialiasing);  // 抗锯齿

  float r = gridWidth / 3;  // 皇后半径

  for (int i = 0; i <= n; ++i) {  // 画棋盘线条
    painter.drawLine(startX, startY + gridWidth * i, startX + n * gridWidth,
                     startY + gridWidth * i);
    painter.drawLine(startX + gridWidth * i, startY, startX + i * gridWidth,
                     startY + gridWidth * n);
  }
  // 画皇后
  if (m_board != nullptr) {
    for (int i = 0; i < n; ++i) {  // 遍历每个格子
      for (int j = 0; j < n; ++j) {
        if (m_board[i][j] == EightQueenSolver::QUEEN) {
          // 画出皇后
          painter.setBrush(QBrush(QColor(250, 180, 250)));  // 填充粉紫色
          painter.drawEllipse(QPointF(startX + gridWidth * (j + 0.5),
                                      startY + gridWidth * (i + 0.5)),
                              r, r);
        }
      }
    }
  }
  if (m_board1d != nullptr) {
    for (int i = 0; i < n; ++i) {
      int j = m_board1d[i];
      if (j >= 0) {
        // 画出皇后
        painter.setBrush(QBrush(QColor(250, 180, 250)));  // 填充粉紫色
        painter.drawEllipse(QPointF(startX + gridWidth * (j + 0.5),
                                    startY + gridWidth * (i + 0.5)),
                            r, r);
      }
    }
  }
}
